package com.chen.rest;

import com.alibaba.dubbo.config.ReferenceConfig;
import com.alibaba.dubbo.rpc.service.GenericService;
import com.alibaba.fastjson.JSON;
import com.chen.JsonNavigator;
import com.chen.JsonUtils;
import org.I0Itec.zkclient.ZkClient;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;

import java.util.List;

public class RestForRpcServiceImpl implements RestForRpcService {

    private static final Integer TIME_OUT = Integer.MAX_VALUE;
    
    private @Autowired ApplicationContext applicationContext;
    private static final Logger logger = LogManager.getLogger(RestForRpcServiceImpl.class);

    @Override
    public Object restForRpc(String requestParams) {
        logger.info("request received {}", requestParams);
        JsonNavigator jsonNav = JsonUtils.json2Object(requestParams);
        // dubbo服务地址及端口号
        String url = jsonNav.getString("url");//dubbo服务地址及端口号
        // rpc接口全类名
        String className = jsonNav.getString("className");
        // url
        String rUrl = url + "/" + className;
        // 方法名
        String methodName = jsonNav.getString("methodName");
        // 参数全类名
        String paramsClassName = jsonNav.getString("paramsClassName");
        // dubbo.group
        String group = jsonNav.getString("group");
        // dubbo.version
        String version = jsonNav.getString("version");
        String str = jsonNav.getString("params");
        // rpc接口参数
        Object params = JSON.parse(str);

        ReferenceConfig<GenericService> reference = new ReferenceConfig<GenericService>();
        reference.setInterface(className);
        reference.setGroup(group);
        reference.setVersion(version);
        reference.setGeneric(true);
        reference.setTimeout(TIME_OUT);
        GenericService genericService = reference.get();
        Object result = genericService.$invoke(methodName, new String[] {paramsClassName}, new Object[] {params});
        return JsonUtils.object2Json(result);
    }
}
